<template>
  <view class="wifiQR">
    <view class="input-group">
      <u-form ref="uForm" :model="form" label-width="100px">
        <u-form-item :label="$t('设备ID')" prop="deviceId" required>
          <u-input v-model="form.deviceId" disabled :placeholder="$t('请选择')" />
          <u-button size="mini" type="primary" @click="selection">{{$t('选取')}}</u-button>
        </u-form-item>
        <u-form-item label="WIFI" prop="wifiSsid" required>
          <u-input v-model="form.wifiSsid" />
        </u-form-item>
        <u-form-item :label="$t('密码')">
          <u-input v-model="form.wifiPwd" type="password" />
        </u-form-item>
      </u-form>
      <u-button style="margin-top: 40px" type="primary" @click="setOCR">{{$t('生成二维码')}}</u-button>
    </view>
    <u-popup v-model="popup.show" mode="center">
      <view class="u-popup">
        <canvas id="qrcode" canvas-id="qrcode" style="width: 640rpx; height: 640rpx" />
      </view>
    </u-popup>

    <u-no-network></u-no-network>
  </view>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import CODE from '@uni-plugs/uni-code'

export default {
  computed: {
    ...mapGetters(['userInfo', 'api', 'qrcode'])
  },
  data() {
    return {
      form: {
        //已选择的值
        deviceId: '',
        wifiSsid: '',
        wifiPwd: ''
      },
      rules: {
        deviceId: [
          {
            required: true,
            message: this.$t('必填')
          }
        ],
        wifiSsid: [
          {
            required: true,
            message: this.$t('必填'),
            trigger: ['change', 'blur']
          }
        ]
      },
      popup: {
        show: false
      }
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  onLoad() {
    uni.setNavigationBarTitle({title: this.$t('设备绑定')})
    //接收印章
    uni.$off('data_cover')
    uni.$on('data_cover', (res) => {
      this.form.deviceId = res.value
    })
  },
  methods: {
    selection() {
      uni.navigateTo({
        url: '../../template/index-list/index-list?type=OCR印章'
      })
    },
    setOCR() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.qrcode.code = encodeURIComponent(JSON.stringify(this.form))
          this.popup.show = true
          this.$nextTick(() => {
            CODE.QRCode(this.qrcode)
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wifiQR {
  background-color: #f0f0f0;
  height: 100%;
  overflow: auto;

  .input-group {
    padding: 20rpx 40rpx;
    background-color: #fff;

    .primary {
      margin-top: 40rpx;
    }
  }

  .u-popup {
    padding: 20rpx;
    border-radius: 20rpx;
  }
}
</style>
